package com.fingard.dsp.bank.directbank.citic02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryRecAuthInfoDetail;
import com.fingard.dsp.bank.reqrespobj.contract.ContractState;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;


public class CITIC02AuthorizeForRec extends CITIC02Base implements IAuthorizeForRec {

    @Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo retAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        retAts.ownAct = p_req.ownAct;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
                retAts.writeAfterDetail();
                return retAts;
            }

            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.Date8Format.parse(p_req.dateFrom));

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(Format.Date8Format.parse(p_req.dateTo));

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                FtpSet ftpSet = bankFront.getFtpSet("auth");
                MixFtp mixFtp = new MixFtp(ftpSet);
                ArrayList<String> fileNameList = mixFtp.listNames(ftpSet.downDir);
                if (fileNameList == null || fileNameList.size() == 0) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "目录：" + ftpSet.downDir + "下无任何文件";
                    retAts.writeAfterDetail();
                    return retAts;
                }
                String queryDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
                for (String eachName : fileNameList) {
                    // 文件名称：固定标识_业务名称_日期+商户协议编号+序号.扩展名  例如：S5IP_ZLDS_QYWJTS20200227ZLDS201901188020001.utf
                    String mccprtcno = eachName.substring(24, 39);//商户协议编号
                    String tmpQrySendDate = eachName.substring(16, 23);//日期
                    // 文件以S5IP_ZLDS_QYWJTS开头 && 文件以.utf结尾 && 商户协议编号与配置的协议号相等 && 文件名中的日期与接收请求查询日期相同
                    if (eachName.startsWith("S5IP_ZLDS_QYWJTS") && eachName.endsWith(".utf") && mccprtcno.equals(actItem.appId) && tmpQrySendDate.equals(queryDate)) {
                        String localFilePath = createTempFileDirectory() + File.separator + eachName;
                        FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(localFilePath, ftpSet.upDir, eachName);
                        String seqNo = eachName.substring(39, 43);// 文件序号
                        if (ftpReceiver.isCompleted) {
                            WriteBankLogLn2("序号[" + seqNo + "]签约文件保存本地路径: " + localFilePath);
                            String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
                            WriteBankLogLn2("序号[" + seqNo + "]签约文件内容:\r\n" + tmpStrRet);
                            if (StringHelper.hasAnyChar(tmpStrRet)) {
                                retAts.respCode = "0";
                                StringReader strReader = new StringReader(tmpStrRet);
                                BufferedReader tmpReader = new BufferedReader(strReader);

                                while (true) {
                                    String tmpLine = tmpReader.readLine();
                                    if (tmpLine == null) {
                                        break;
                                    }
                                    String[] eachLine = tmpLine.split("\\|");
                                    RetAtsQryRecAuthInfoDetail tmpRetDetail = new RetAtsQryRecAuthInfoDetail();
                                    tmpRetDetail.oppAct = eachLine[1];
                                    tmpRetDetail.oppActName = eachLine[2];
                                    tmpRetDetail.newAuthCode = eachLine[0];
                                    tmpRetDetail.signDate = Format.Date8Format.format(eachLine[4]);
                                    tmpRetDetail.certType = convertCertTypeToBank(eachLine[3]);
                                    String signState = eachLine[10];
                                    if ("1".equals(signState)) {
                                        tmpRetDetail.signState = ContractState.SUCCESS;
                                    } else {
                                        tmpRetDetail.signState = ContractState.UNSIGNED;
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "签约文件内容为空!";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "序号[" + seqNo + "]签约文件下载失败:" + ftpReceiver.connMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "无符合条件的签约文件!";
                    }
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}